package com.myblog.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myblog.Utils.BeanCopyUtils;
import com.myblog.Utils.SecurityUtils;
import com.myblog.Utils.WebUtils;
import com.myblog.domain.GlobalResponse;
import com.myblog.domain.Vo.AdminUserVo;
import com.myblog.domain.Vo.UserInfoVo;
import com.myblog.domain.dto.GetUserDto;
import com.myblog.domain.dto.UserDto;
import com.myblog.domain.entity.Role;
import com.myblog.domain.entity.User;
import com.myblog.domain.entity.UserRole;
import com.myblog.domain.entity.enums.GlobalResponseEnum;
import com.myblog.expection.GlobalException;
import com.myblog.services.RoleService;
import com.myblog.services.UserRoleService;
import com.myblog.services.UserService;
import com.myblog.mapper.UserMapper;
import io.jsonwebtoken.lang.Strings;
import org.omg.CORBA.SystemException;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2022-09-27 09:25:26
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService{

    @Resource
    UserRoleService userRoleService;
    @Override
    public GlobalResponse getUserInfo() {
        User user = getById(SecurityUtils.getUserId());
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        return GlobalResponse.ok(userInfoVo);
    }

    @Override
    public GlobalResponse updateUserInfo(User user) {
        updateById(user);
        return GlobalResponse.ok();
    }


    @Resource
    PasswordEncoder passwordEncoder;
    @Override
    public GlobalResponse register(User user) {
        //对数据做非空判断
        if(!Strings.hasText(user.getUserName())){
            throw new GlobalException(GlobalResponseEnum.REQUIRE_USERNAME);
        }
        if(!Strings.hasText(user.getPassword())){
            throw new GlobalException(GlobalResponseEnum.REQUIRE_PASSWORD);
        }
        if(!Strings.hasText(user.getNickName())){
            throw new GlobalException(GlobalResponseEnum.REQUIRE_NICKNAME);
        }
        if(!Strings.hasText(user.getEmail())){
            throw new GlobalException(GlobalResponseEnum.REQUIRE_EMAIL);
        }
        //对数据是否存在做判断
        if(userNameExits(user.getUserName())){
            throw new GlobalException(GlobalResponseEnum.USERNAME_EXIST);
        }
        if(nickNameExits(user.getNickName())){
            throw new GlobalException(GlobalResponseEnum.NICKNAME_EXIST);
        }

        //加密密码
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        //存入数据库
        save(user);
        return GlobalResponse.ok();


    }

    @Override
    public GlobalResponse addUser(UserDto userDto) {
        if(Objects.isNull(userDto.getUserName())){
            return GlobalResponse.error(GlobalResponseEnum.REQUIRE_USERNAME);
        }else{
            LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getUserName,userDto.getUserName());
            User one = getOne(lambdaQueryWrapper);
            System.out.println(one);
            if(Objects.nonNull(one)){
                return GlobalResponse.error(GlobalResponseEnum.USERNAME_EXIST);
            }
        }

        if(Strings.hasText(userDto.getEmail())){
            LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getEmail,userDto.getEmail());
            User one = getOne(lambdaQueryWrapper);
            if(Objects.nonNull(one)){
                return GlobalResponse.error(GlobalResponseEnum.EMAIL_EXIST);
            }
        }else{
            return GlobalResponse.error(GlobalResponseEnum.REQUIRE_EMAIL);
        }

        if(Strings.hasText(userDto.getPhonenumber())){
            LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhonenumber,userDto.getPhonenumber());
            User one = getOne(lambdaQueryWrapper);
            if(Objects.nonNull(one)){
                return GlobalResponse.error(GlobalResponseEnum.PHONENUMBER_EXIST);
            }
        }else{
            return GlobalResponse.error(GlobalResponseEnum.NEED_PHONE);
        }

        String encode = passwordEncoder.encode(userDto.getPassword());
        userDto.setPassword(encode);

        User user=BeanCopyUtils.copyBean(userDto,User.class);

        save(user);
        List<String> roleIds = userDto.getRoleIds();
        List<UserRole> userRoleList = roleIds.stream().map(roleId -> new UserRole(user.getId(), Long.parseLong(roleId)))
                .collect(Collectors.toList());
        userRoleService.saveBatch(userRoleList);
        return GlobalResponse.ok();
    }

    @Override
    public GlobalResponse deleteUser(Long id) {
        Long userId = SecurityUtils.getUserId();
        if(id.equals(userId)){
            return GlobalResponse.error(GlobalResponseEnum.ERROR.getCode(),"不能删除当前用户");
        }
        removeById(id);
        return GlobalResponse.ok();
    }

@Resource
    RoleService roleService;
    @Override
    public GlobalResponse getUser(Long id) {
        User user = getById(id);

        GetUserDto getUserDto = BeanCopyUtils.copyBean(user, GetUserDto.class);

        LambdaQueryWrapper<UserRole> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRole = userRoleService.list(lambdaQueryWrapper);
        List<Long> roleIds = userRole.stream()
                .map(userRole1 -> userRole1.getRoleId())
                .collect(Collectors.toList());

        List<Role> roleList = roleService.listByIds(roleIds);
        return GlobalResponse.ok(new AdminUserVo(getUserDto,roleIds,roleList));
    }

    @Override
    public GlobalResponse updateUser(GetUserDto userDto) {
        User user = BeanCopyUtils.copyBean(userDto, User.class);
        if(!updateById(user)){
            return GlobalResponse.error(GlobalResponseEnum.ID_NO_EXIST);
        }

        List<Long> roleIds = userDto.getRoleIds();
        List<UserRole> userRoleList = roleIds.stream()
                .map(roleId -> new UserRole(user.getId(), roleId))
                .collect(Collectors.toList());

        LambdaQueryWrapper<UserRole> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserRole::getUserId,user.getId());
        userRoleService.remove(lambdaQueryWrapper);

        userRoleService.saveBatch(userRoleList);

        return GlobalResponse.ok();
    }

    public boolean userNameExits(String userName){
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName,userName);
        return count(lambdaQueryWrapper)>0;
    }


    public boolean nickNameExits(String nickName){
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getNickName,nickName);
        return count(lambdaQueryWrapper)>0;
    }


}
